#include "mainwindow.h"

#include <QDockWidget>
#include <QMenu>
#include <QMenuBar>
#include <QAction>
#include <QFileDialog>

#include "render.h"
#include "panel.h"

#include "delaunay.h"
#include "vector.h"

#include <cstdlib>

std::vector<Tut::Vector> test(void) {
	using namespace Tut;
	std::vector<Vector> points;
	points.push_back(Vector(0.0,0.0,0.0,1));
	points.push_back(Vector(1.0,0.0,0.0,2));
	points.push_back(Vector(1.0,1.0,0.0,3));
	points.push_back(Vector(0.0,2.0,0.0,4));
	points.push_back(Vector(0.5,0.5,0.0,5));
	/*srand(0);
	points.push_back(Vector(10.0,-10.0));
	for(int i =0; i < 500; i++) {
		int random = rand()%9;
		int random2 = rand()%9;
		int random3 = rand()%2;
		int random4 = rand()%2;
		if(random3 == 1)
			random2*=-1;
		if(random4 == 1)
			random*=-1;
		points.push_back(Vector(random, random2));
	}*/
	return points;
}

namespace Ui {

MainWindow::MainWindow(QWidget* _parent) : QMainWindow(_parent), input() { 
	render = new Render(this);
	panel = new Panel(this);
	panel_dock = new QDockWidget();
	menubar = new QMenuBar();
	QMenu* menu = new QMenu("File", menubar);
	menubar->addMenu(menu);
	QAction* open_file = new QAction("&Open", menu);
	QAction* exit = new QAction("&Exit", menu);
	menu->addAction(open_file);
	menu->addSeparator();
	menu->addAction(exit);

	connect(open_file, SIGNAL(triggered()), this, SLOT(open_file()));

	panel_dock->setWidget(panel);

	addDockWidget(Qt::LeftDockWidgetArea, panel_dock);
	setMenuBar(menubar);
	calculate();
	setCentralWidget(render);
}

MainWindow::~MainWindow(void) { 
	delete render;
}

void MainWindow::points_visualization_changed(int value) {
	render->set_points_visualization(value);
}

void MainWindow::triangulation_visualization_changed(int value) {
	render->set_triangulation_visualization(value);
}

void MainWindow::viewport_changed(int value) {
	render->set_viewport_scale(value);
}


void MainWindow::open_file(void) {
	QString filename = QFileDialog::getOpenFileName(this,tr("Open File"), QDir::currentPath(),tr("Convex Hull 2d Files (*.ch2d)"));
	if(!filename.isEmpty())	{
		input = boost::shared_ptr<Tut::Input>(new Tut::Input(filename.toStdString()));
		calculate();
	}

}

void MainWindow::calculate(void) {
	//if(input) {
		render->clear_points();
		render->clear_triangulation();
		//std::vector<Tut::Vector> points = input->parse();
		std::vector<Tut::Vector> points = test();
		Tut::Delaunay del(points);
		std::vector<Tut::Edge> result =  del.triangulation();
		render->set_points(points);
		render->set_triangulation(result);
//	}
}


}

